package com.example.origin.mysql.controller;

import com.example.origin.mysql.domain.User;
import com.example.origin.mysql.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("user")
@RestController
public class UserController {


    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserService userService;


    @GetMapping("/supportedTransaction")
    public boolean supportedTransaction() {
        try (Connection connection = dataSource.getConnection()) {
            DatabaseMetaData databaseMetaData = connection.getMetaData();
            return databaseMetaData.supportsTransactions();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    @GetMapping
    public User getUser(@RequestParam(value = "id", defaultValue = "1") int id) {
        return userService.getUser(id);
    }

    @PostMapping
    public Map<String, Object> addUser(@RequestBody User user) {
        Map<String, Object> data = new HashMap<>();
        if (user.getId()%2==0) {
            data.put("save", userService.save(user));
        }else {
            data.put("save2", userService.save2(user));
        }
        return data;
    }

}